<?php

namespace app\common\service;

use app\common\job\PromotionCallback;
use app\common\model\PromotionGroupFeedback;
use app\common\model\Trade;
use ShidianUtil\Utils\ConvertUtil;
use think\facade\Log;
use think\facade\Queue;

/**
 * 订单付费回传事件处理
 * Class PromotionCallbackService
 * @package app\common\service
 */
class PromotionCallbackService
{

    /**
     * @param Trade $trade
     * @return void
     */
    public function push(Trade $trade)
    {
        $params = $trade->attach['promotionFeedback'] ?? null;

        if (!is_array($params)) {
            return;
        }

        $promotionActionId = $params['promotionActionId'] ?? null;
        // $params['clickid'] ??= '';
        // $params['logidUrl'] ??= '';

        if (!is_id($promotionActionId)) {
            return;
        }

        // 渠道链路
        $pf = $trade->pf;
        $chain = $trade->chain;
        $promotionGroupId = $trade->promotionGroupId;

        $this->pushEventsByActionId($promotionActionId, $promotionGroupId, $chain, $pf, $params);
    }

    public function pushEventsByActionId($promotionActionId, $promotionGroupId, $chain, $pf, $params)
    {
        $params['promotionActionId'] = $promotionActionId;
        $params['promotionGroupId'] = $promotionGroupId;
        $params['chain'] = $chain;
        $params['pf'] = $pf;

        // 查询对应的回传配置
        PromotionGroupFeedback::where('promotionGroupId', $promotionGroupId)
            ->where('isSel', 101)
            ->whereRaw("FIND_IN_SET($promotionActionId,`actionIds`)")
            ->append(['deductionProportionOrigin'])
            ->select()
            ->each(function (PromotionGroupFeedback $feedback) use ($params) {
                // 添加任务
                $params['promotionEventId'] = $feedback->promotionEventId;
                $params['deductionBase'] = $feedback->deductionBase;
                $params['deductionProportionOrigin'] = $feedback->deductionProportionOrigin;
                Queue::push(PromotionCallback::class, $params);
            });
    }
}